﻿using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using WCS.Entities.User;

namespace WCS.Tools
{

    public static class JwtHelper
    {

        public static string CreateToken(IConfiguration _configuration, UserInfo userInfo)
        {
			try
			{
				// 1. 定义需要使用到的Claims
				var rolesClaim = new List<Claim>();
				rolesClaim.Add(new Claim(ClaimTypes.Role, userInfo.Role.ToString()));
				var claims = new[]
				{
				new Claim(ClaimTypes.Name, userInfo.UserName), //HttpContext.User.Identity.Name
                new Claim(JwtRegisteredClaimNames.Jti, userInfo.UserId.ToString()),
			};

				rolesClaim.AddRange(claims);
				// 2. 从 appsettings.json 中读取SecretKey
				var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));
				// 3. 选择加密算法
				var algorithm = SecurityAlgorithms.HmacSha256;
				// 4. 生成Credentials
				var signingCredentials = new SigningCredentials(secretKey, algorithm);
				// 5. 根据以上，生成token
				var jwtSecurityToken = new JwtSecurityToken(
				   issuer: _configuration["Jwt:Issuer"],     //Issuer
				   audience: _configuration["Jwt:Audience"],   //Audience
				   claims: claims,                          //Claims,
				   expires: DateTime.Now.AddHours(3),    //expires
				   signingCredentials: signingCredentials               //Credentials
				);
				// 6. 将token变为string new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken)
				var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
				return token;
			}
			catch (Exception ex)
			{
				throw;
			}
        }
    }
}
